from flask import Blueprint, jsonify, request, session, abort
from models.entity.button import Button
from models.entity.module import Module
import json
from appserver import execute_sql, sql_row_to_dict
from utils.nodetree import get_all_button
from utils.result import result

mod = Blueprint("core_button", __name__, url_prefix="/core/button", template_folder="templates", static_folder="static")
# 2018.4.2 修改完成


@mod.route('/del/',methods=['POST'])
def del_button_item():
    """删除按钮"""
    # receive = request.get_data()
    # receive = request.data
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0, error_code=-1, error_msg='数据格式错误')
    button_id = data['id']
    # parent_id = data.get('parent_id', '')
    # print('parent_id',parent_id)
    # if button_id not in [p["id"] for p in session["auth"]["buttons"]]:
    #     return abort(403)
    # 查找对应的button
    button = Button.get_button_by_id(button_id)
    if not button:
        return result(success=0,error_code=-2,error_msg="当前按钮不存在")
    # 检查该的是否存在依赖性
    if button.child_num != 0 or button.depth !=1:
        return result(success=0, error_code=-1, error_msg="该按钮仍然有子按钮,不能删除")
    # buttons = Button().get_list_by_pid(parent_id)
    # buttons = button.get_list_by_pid(parent_id)
    # print('buttons', buttons)
    # 如果存在依赖性，则不能删除对应的按钮   ,这个地方还有点问题,就是依赖的地方,所以我把下面两行注释了
    # if len(buttons):
    #     return result(success=0,error_code=-1,error_msg="该按钮仍然有子按钮,不能删除")
    if button.delete():
        return jsonify(success=1)
    else:
        return result(success=0,error_code=-2,error_msg="未知错误")


@mod.route('/add/',methods=['GET','POST'])
def add_button():
    """添加按钮"""  # 正常
    """
    {
    "name":"lihongzhi",
    "code":"falungong",
    "module_id":8,
    "ParentId":0,
    "dis_order":0,
    "target":1,
    "icon":"fff",
    "status":1,
    "url":""
    }
    """
    # receive = request.get_data()
    # receive = request.data
    # print('receive', receive)
    data = json.loads(request.data.decode("utf-8"))
    if 'name' not in data:
        return result(success=0,error_code=-2,error_msg="名称不能为空")
    if 'code' not in data:
        return result(success=0,error_code=-2,error_msg="编码不能为空")
    if 'module_id' not in data:
        return result(success=0,error_code=-2,error_msg="模块不能为空")
    if data["name"] == ".":
        return result(success=0, error_code=-2, error_msg="按钮的名字不能为\".\"")
    # if data['module_id'] not in [p["id"] for p in session["auth"]["module_list"]]:
    #     return abort(403)
    # if data["ParentId"] not in [p["id"] for p in session["auth"]["buttons"]]:
    #     return abort(403)
    if data["name"] in [n.name for n in Button().get_list_by_pid(data["parent_id"])]:
        return result(success=0,error_code=-4,error_msg="当前层级下该名字已被占用")
    if not Module().get_entity_by_id(data["module_id"]):
        return result(success=0,error_code=-4,error_msg="模块存在异常")
    if Button.get_button_by_code(data["code"]):
        return result(success=0,error_code=-4,error_msg="按钮编号已被占用")
    if (data["parent_id"]!=0) and (Button().get_entity_by_id(data["parent_id"]) is None):
        return result(success=0,error_code=-5,error_msg="上层节点存在异常")
    try:
        button = Button()
        # button.id = data.get('id')  # 不传这个参数
        button.name = data.get('name')
        button.code = data.get('code')
        button.parent_id = data.get('parent_id')
        button.module_id = data.get('module_id')
        button.module_id = data.get('icon')
        button.module_id = data.get('status')
        button.module_id = data.get('url')
        print(1111111,button.module_id)
        button.from_dict(data)
        if button.save() is False:
            print('错误111111')
            return result(success=0,error_code=-1,error_msg="保存错误")
        return result(success=1)
    except RuntimeError as e:
        return result(success=0,error_code=-3,error_msg=str(e))


@mod.route('/edit/',methods=['POST'])
def edit_button():
    """编辑按钮"""
    """该按钮允许不允许改变父类和模型，值得商榷"""
    """
    {
    "id":3,
    "name":"ldd",
    "code":"fgg",
    "module_id":8,
    "ParentId":0,
    "dis_order":0,
    "target":1,
    "icon":"fff",
    "status":1,
    "url":""
    }
    data {'url': '', 'path': '6', 'level': 1, 'dis_order': 0, 'code': '123123', 'name': '123', 'status': 'on',
    'icon': 'fa fa-folder-o', 'target': None, 'id': 6, 'parent_id': 0, 'child_num': 0, 'module_id': 2}

    """
    # receive = request.get_data()
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0, error_code=-1, error_msg='数据格式错误')
    button = Button.query.filter_by(id=data["id"]).first()
    print('button', button)
    if 'name' not in data:
        return result(success=0,error_code=-2,error_msg="名称不能为空")
    if 'code' not in data:
        return result(success=0,error_code=-2,error_msg="编码不能为空")
    # if "module_id" in data:  # 5
    #     if Button.get_button_by_id(data["parent_id"]).module_id != data['module_id']:
    #         return result(success=0,error_code=-2,error_msg="模块和上级模块不匹配")
    if data["name"] != button.name and Button.query.filter_by(parent_id=data["parent_id"]).filter_by(name=data["name"]).first():
        return result(success=0,error_code=-1,error_msg="同级按钮不可重名")
    # if data['module_id'] not in [p["id"] for p in session["auth"]["module_list"]]:
    #     return abort(403)
    # if data["parent_id"] not in [p["id"] for p in session["auth"]["buttons"]]:
    #     return abort(403)
    try:
        button.from_dict(data)
    except RuntimeError as e:
        return result(success=0,error_code=-2,error_msg=str(e))
    if button.save() is False:
        return result(success=0,error_code=-1,error_msg="保存错误")
    return result(success=1)


@mod.route("/get_all_by_module_id/", methods=["GET", "POST"])
def get_all_by_module_id():
    try:
        data=json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0,error_code=-1,error_msg="json format error")
    all_buttons = Button.get_buttons_by_module_id(data["id"])
    rdic = {}
    rdic["data"] = []
    for item in all_buttons:
        rdic["data"].append(item.to_dict())
    return result(data=rdic['data'])


@mod.route('/get_tree/',methods=['GET','POST'])
def get_tree():
    """得到按钮树"""   # 已测, 正常
    button_root = Button().get_list_by_pid(0)  # 得到所有的根节点
    rlist = []
    for item in button_root:
        t = Button().get_tree_by_pid(item.id)
        if len(t) > 0:
            rlist.append(t[0])
    return result(success=1,data=rlist)


@mod.route("/get_tree_by_module_id/",methods=["POST","GET"])
def get_tree_by_module_id_interface():
    """
    根据模块id获取其按钮树    # 已测, 正常
    """
    # request: json
    # {
    #       id:id
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
        # print('request.args',request.args)
        # data = request.args.decode("utf-8")
        print('data', data)
    except:
        return result(success=0,error_code=-1,error_msg="json format error")
    if not "id" in data:
        return result(success=0,error_code=-2,error_msg="id不在json中")
    else:
        id_num=data["id"]
    if not isinstance(id_num,int):
        return result(success=0,error_code=-3,error_msg="id必须为整数")
    t = Button().get_button_tree_by_module(Module().get_entity_by_id(id_num))
    return result(success=1,data=t)

@mod.route("/get_tree_by_module_id_list/",methods=["POST"])
def get_tree_by_module_id_list_interface():
    """
    根据模块id组获取其按钮树   正常
    """
    # request: json
    # {
    #      id: [id_1,id_2,id_3, ...]
    # }
    def travel_tree(source):
        # 将模块与按钮放在一棵树下
        def in_travel_tree(id_num):
            sz=[]
            for obj in source:
                if isinstance(obj,Module):
                    if obj.parent_id==id_num:
                        dic=obj.to_dict()
                        buttons=Button.get_buttons_by_module_id(obj.id)
                        if (len(Module().get_list_by_pid(obj.id))==0) and (len(buttons)!=0):
                            # 如果该模块不是菜单并且有按钮
                            dic["children"]=[]
                            for item in buttons:
                                if item.name == ".":
                                    continue
                                dic["children"].append(Button.get_button_dic(item))
                        else:
                            dic["children"]=in_travel_tree(obj.id)
                        sz.append(dic)
            return sz
        rlist=in_travel_tree(1)
        return rlist
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0,error_code=-1,error_msg="json format error")
    if not "id" in data:
        return result(success=0,error_code=-2,error_msg="id不在json中")
    else:
        id_list= data["id"]
    if not isinstance(id_list,list):
        error_msg={
                        "success":0,
                        "error_code":-3,
                        "error_msg":"id must be a list"
                }
        return result(success=0,error_code=-3,error_msg="id不是列表")
    all_node=[]
    for id_num in data["id"]:
        all_node.append(Module().get_entity_by_id(id_num))
        buttons=Button.get_buttons_by_module_id(id_num)
        for button in buttons:
            all_node.append(button)
    # print("%s" %(travel_tree(all_node)))
    # print("%s" %(str(all_node)))
    return result(success=1,data=travel_tree(all_node))

########我加的方法8-28
@mod.route("/get_buttons_by_module_id_list/",methods=["POST"])
def get_buttons_by_module_id_list():
    """
    根据模块id组获取其按钮树   正常
    """
    # request: json
    # {
    #      id: [id_1,id_2,id_3, ...]
    # }
    # def travel_tree(source):
    #     # 将模块与按钮放在一棵树下
    #     def in_travel_tree(id_num):
    #         sz=[]
    #         for obj in source:
    #             if isinstance(obj,Module):
    #                 if obj.parent_id==id_num:
    #                     dic=obj.to_dict()
    #                     buttons=Button.get_buttons_by_module_id(obj.id)
    #                     if (len(Module().get_list_by_pid(obj.id))==0) and (len(buttons)!=0):
    #                         # 如果该模块不是菜单并且有按钮
    #                         dic["children"]=[]
    #                         for item in buttons:
    #                             if item.name == ".":
    #                                 continue
    #                             dic["children"].append(Button.get_button_dic(item))
    #                     else:
    #                         dic["children"]=in_travel_tree(obj.id)
    #                     sz.append(dic)
    #         return sz
    #     rlist=in_travel_tree(1)
    #     return rlist
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0,error_code=-1,error_msg="数据格式错误")
    if not "id" in data:
        return result(success=0,error_code=-2,error_msg="id不在json中")
    else:
        id_list=data["id"]
    if not isinstance(id_list,list):
        error_msg={
                        "success":0,
                        "error_code":-3,
                        "error_msg":"必须是一个列表"
                }
        return result(success=0,error_code=-3,error_msg="id不是列表")
    dic = {}
    # all_modules=[]
    all_buttons=[]
    for id_num in id_list:
        # all_modules.append(Module().get_entity_by_id(id_num))
        # buttons=Button.get_buttons_by_module_id(id_num)
        t = Button().get_button_tree_by_module(Module().get_entity_by_id(id_num))
        for i in t:
        # print('t', t[0])
        # else:
        #     dic["children"] = in_travel_tree(obj.id)
        # for button in buttons:
        #     if button.child_num != 0:
        #         # 如果该模块不是菜单并且有按钮
        #         dic["children"] = []
        #         for item in buttons:
        #             if item.name == ".":
        #                 continue
        #             dic["children"].append(item.to_dict())
        #         all_buttons.append(dic)
        #     all_buttons.append(button.to_dict())
            all_buttons.append(i)
    print(all_buttons)
    # print("%s" %(travel_tree(all_node)))
    # print("%s" %(str(all_node)))
    return result(success=1, data=all_buttons)

@mod.route("/search/",methods=["POST"])
def search_button():
    """
    查询button       正常
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        receive = request.get_data()
        data = json.loads(receive.decode("utf-8"))
        tmp ={}
        extra =[]
        if 'query_word' in data:
            query_word = data['query_word']
        else:
            return result(success=0,error_code=-9,error_msg="数据格式错误")
        buttons = Button.search(query_word)
        return jsonify(buttons)

